<template>
    <el-card>
        <el-button type="primary" @click="dialogVisible = true">新建</el-button>

        <template #header>
            <div>
                轮播管理
            </div>
        </template>
        <el-table :data="bannerData">
            <el-table-column label="ID" prop="id">
            </el-table-column>
            <el-table-column label="图片" prop="thumb">
                <template #default="{ row }">
                    <img :src="api.baseURl + row.thumb" alt="" width="300" height="150">
                </template>
            </el-table-column>
            <el-table-column label="状态" >
                <template #default="{row}" prop="state">
                    <el-switch :active-value="1" :in-active-value="0" v-model="row.state"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="商品" prop="gid">
            </el-table-column>
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button type="warning" @click="handleEdit(row)">编辑</el-button>
                    <el-button type="danger" @click="handleDelete(row.id)">删除</el-button>
                </template>

            </el-table-column>
        </el-table>
        <el-row style="height:60px;" align="middle" justify="center">
            <el-pagination background layout="prev, pager, next" :total="total" v-model:page-size="pageSize"
                v-model:current-page="page" @current-change="getdata" />
        </el-row>
        <!-- 弹窗 -->
        <el-dialog v-model="dialogVisible" title="新增轮播" width="500">
            <el-form label-width="80px" :model="addForm" :rules="rules" ref="formIns">
                <el-form-item label="轮播图" prop="thumb">
                    <el-upload class="avatar-uploader" :action="api.UPLOAD" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="addForm.thumb" :src="api.baseURl + addForm.thumb" class="avatar" />

                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                        <template #tip>
                            <div class="el-upload__tip">
                                请上传jpg/png图片,并且小于200kb
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
                <el-form-item label="显示状态">
                    <el-switch :active-value="1" :in-active-value="0" v-model="addForm.state"></el-switch>
                </el-form-item>
                <el-form-item label="对应商品">
                    <el-input v-model="addForm.gid"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handlesubmit">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 编辑弹框 -->
        <el-dialog v-model="dialogVisible2" title="编辑" width="500">
            <el-form label-width="80px" :model="editForm" :rules="rules" ref="formIns2">
                <el-form-item label="轮播图" prop="thumb">
                    <el-upload class="avatar-uploader" :action="api.UPLOAD" :show-file-list="false"
                        :on-success="handleAvatarSuccess2" :before-upload="beforeAvatarUpload2">
                        <img v-if="editForm.thumb" :src="api.baseURl + editForm.thumb" class="avatar" />

                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                        <template #tip>
                            <div class="el-upload__tip">
                                请上传jpg/png图片,并且小于200kb
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
                <el-form-item label="状态" prop="state">
                    <el-input v-model="editForm.state"></el-input>
                </el-form-item>
                <el-form-item label="商品" prop="gid">
                    <el-input v-model="editForm.gid"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible2 = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit2">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { getBanner, addBanner, findbyrid, delBanner, edtBanner, getMenu } from '@/api/api';
import type { FormRules, FormInstance } from "element-plus"
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Action } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import api from "../api/url"
// 查看
const bannerData = ref<BannerData[]>([]);
const roleData = ref<RoleData[]>([]);
onMounted(() => {
    getdata();
})
const pageSize = ref(5);
const total = ref(0);
const page = ref(1);
const getdata = async () => {
    const res = await getBanner({
        page: page.value,
        limit: pageSize.value
    });
    bannerData.value = res.data.data;
    total.value = res.data.total
}

// 弹框
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    console.log(response);
    addForm.thumb = response.url;

}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type != 'image/png') {
        ElMessage.error('图片格式必须为jpg或者png!')
        return false
    } else if (rawFile.size / 1024 > 200) {
        ElMessage.error('图片大小不能超过200k!')
        return false
    }
    return true
}

// 编辑弹框
const handleAvatarSuccess2: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    console.log(response);
    editForm.thumb = response.url;

}

const beforeAvatarUpload2: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type != 'image/png') {
        ElMessage.error('图片格式必须为jpg或者png!')
        return false
    } else if (rawFile.size / 1024 > 200) {
        ElMessage.error('图片大小不能超过200k!')
        return false
    }
    return true
}

const open = () => {
    ElMessageBox.alert('This is a message', 'Title', {
        // if you want to disable its autofocus
        // autofocus: false,
        confirmButtonText: 'OK',
        callback: (action: Action) => {
            ElMessage({
                type: 'info',
                message: `action: ${action}`,
            })
        },
    })
}

// 新增数据
const addForm = reactive<BannerForm>({
    thumb: "",
    state: 0,
    gid: 0
});
const rules: FormRules = {
    thumb: { required: true, message: "请上传图片", trigger: "blur" }
}
const dialogVisible = ref(false)
const formIns = ref<FormInstance>();
const handlesubmit = async () => {
    try {

        await formIns.value?.validate();
        const result = await addBanner(addForm)
        if (result.data.code === 200) {
            ElMessage.success("添加成功");
            dialogVisible.value = false;
            formIns.value?.resetFields();
            getdata();
        } else {
            ElMessage.error("添加失败")
        }
    } catch (error) {

    }

}
// 删除
const handleDelete = async (id: number) => {

    try {
        await ElMessageBox.confirm(
            '确认删除当前角色吗',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        const res = await delBanner(id);
        if (res.data.code === 200) {
            ElMessage.success("删除成功");
            getdata();
        } else {
            ElMessage.error("删除失败");
        }
    } catch (e) {
        ElMessage.info("取消删除")
    }
}
//编辑
const handleChange = async (val: number, id: number) => {
    const res = await edtRole(id, { state: val });
    if (res.data.code === 200) {
        ElMessage.success("修改成功");
    }
}

const dialogVisible2 = ref(false);

const editForm = reactive<BannerForm>({
    thumb: "",
    state: 0,
    gid: 0
});
const formIns2 = ref<FormInstance>();
let eidtid = 0;
const handleEdit = (body: RoleData) => {
    dialogVisible2.value = true;
    editForm.rolename = body.rolename;
    eidtid = body.id;
}
// 权限
const checkedMenu = ref<string[]>([]);
const menu = ref<MenuData[]>([]);
onMounted(async () => {
    const res = await getMenu({ page: 1, limit: 20 })
    menu.value = res.data.data;
})
const dialogVisible3 = ref(false);
const handleEditMenu = (id: number, menu: string) => {


    dialogVisible3.value = true;
    checkedMenu.value = JSON.parse(menu);
    eidtid = id;
}
const handleSubmit3 = async () => {

    const res = await edtRole(eidtid, { menu: JSON.stringify(checkedMenu.value) })
    if (res.data.code === 200) {
        ElMessage.success("修改成功");
        getdata();
        dialogVisible3.value = false;
    }
}
// 编辑弹框确认触发事件
const handleSubmit2 = () => {
    formIns2.value?.validate(async valid => {
        if (valid) {
            const res = await edtBanner(eidtid, editForm)
            console.log(res);

            if (res.data.code === 200) {
                dialogVisible2.value = false;
                getdata();
                ElMessage.success("修改成功");
            } else {
                dialogVisible2.value = false;
                ElMessage.error("修改失败");
            }
        }
    })
}
</script>
<style scoped>
.avatar-uploader .avatar {
    width: 233px;
    height: 106px;
    display: block;
    border: 1px dashed var(--el-border-color);
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 233px;
    height: 106px;
    text-align: center;
    border: 1px dashed var(--el-border-color);
}
</style>